package com.elminster.common.db.analyze;

import java.lang.reflect.Field;

import com.elminster.common.db.exception.SqlAnalyzeException;
import com.elminster.common.util.ReflectUtil;

public class ORMFetchAnalyzer extends ORMSqlAnalyzer {

	@Override
	public SqlType getSqlType() {
		return SqlType.QUERY;
	}

	@Override
	protected void mapping(Object obj) {
		StringBuilder builder = new StringBuilder();
		StringBuilder whereClause = new StringBuilder();
		
		builder.append("SELECT ");
		Field[] fields = ReflectUtil.getAllField(obj.getClass());
		boolean first = true;
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			if (isColumn(field)) {
				if (0 != i) {
					builder.append(", ");
				}
				String columnName = getColumnName(field);
				builder.append(columnName);
				
				Object value = null;
				try {
					value = ReflectUtil.getFieldValue(obj, field);
				} catch (IllegalArgumentException e) {
					throw new SqlAnalyzeException(e);
				} catch (IllegalAccessException e) {
					throw new SqlAnalyzeException(e);
				}
				if (null != value) {
					if (first) {
						whereClause.append(" WHERE ");
						first = false;
					} else {
						whereClause.append(" AND ");
					}
					if (null != value) {
						whereClause.append(columnName);
						whereClause.append(" = ?");
					}
					analyzedSqlParameters.add(value);
				}
			}
		}
		builder.append(" FROM ");
		builder.append(getTableName(obj));
		builder.append(whereClause.toString());
		analyzedSql = builder.toString();
		
	}
}
